﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using ThuySan.Bussiness;

namespace ThuySan.Repository
{
    public class BaseEntityRepository<T, TK>
        where T : DbContext
        where TK : class
    {

        public T DataContext;
        private DbSet<TK> _dbSet;

        protected DbSet<TK> DbSet
        {
            get { return _dbSet ?? (_dbSet = DataContext.Set<TK>()); }
        }

        public void AcceptChanges()
        {
            DataContext.SaveChanges();
        }

        public void AcceptChanges(out Exception exception)
        {
            try
            {
                AcceptChanges();
                exception = null;
            }
            catch (Exception ex)
            {
                foreach (var entry in DataContext.ChangeTracker.Entries())
                {
                    if (entry.State == EntityState.Modified)
                    {
                        entry.State = EntityState.Unchanged;
                    }
                    else if (entry.State == EntityState.Added)
                    {
                        entry.State = EntityState.Detached;
                    }
                    // Handle deleted entities:
                    else if (entry.State == EntityState.Deleted)
                    {
                        entry.State = EntityState.Unchanged;
                    }
                }
                exception = ex;
            }
        }

        protected void SetEntityState(TK value, EntityState entityState)
        {
            if (DataContext.Entry(value).State == EntityState.Detached)
                DbSet.Attach(value);
            DataContext.Entry(value).State = entityState;
        }

        protected void SetEntityState(IEnumerable<TK> value, EntityState entityState)
        {
            if (!(value is List<TK>))
                value = value.ToList();

            foreach (TK k in value.ToList())
            {
                SetEntityState(k, entityState);
            }
        }

        protected void MarkAsDeleted(object obj)
        {
            DataContext.Entry(obj).State = EntityState.Deleted;
        }
    }
}
